package middleware

import (
	"context"
	"gochat/common"
	"gochat/common/enums"
	"gochat/domain/response/result"
	"gochat/utils"
	"log"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm/logger"
)

func IsLoginToken(c *gin.Context) {
	url := c.Request.URL
	path := url.Path
	token := ""

	if path == "/auth/login" || path == "/user/register" || strings.HasPrefix(path, "/auth/login/github/callback") {
		c.Next()
		return
	}
	token = c.GetHeader("token")
	if strings.HasPrefix(path, "/ws") {
		token = c.Query("token")
	}
	if token == "" {
		result.Fail(c, 403, "请登录后再操作")
		c.Abort()
		return
	}
	jwt, err := utils.ValidateToken(token)
	if err != nil {
		log.Println(logger.Blue, "jwt解析失败:", err)
		result.Fail(c, 403, "请登录后再操作")
		c.Abort()
		return
	}
	rdb := common.RDB
	rst := rdb.Get(context.Background(), enums.USER_LOGIN_PREV+jwt.UserID)
	if rst == nil {
		result.Fail(c, 405, "该账号已退出")
		c.Abort()
		return
	}
	if rst.Val() != token {
		result.Fail(c, 405, "该账号已在别处登录")
		c.Abort()
		return
	}
	c.Set("uid", jwt.UserID)
	rdb.Expire(c, enums.USER_LOGIN_PREV+jwt.UserID, time.Hour*24*7)
	c.Next()

}
